// var createHandler = require('github-webhook-handler')
// var handler = createHandler({ path: '/', secret: '9060b6ec90dxxxxxxxxxxxxx' })
const http = require('http')
const webhooks = require('./pkg/gitee-webhook-handler')

const handler = webhooks({ path: '/', token: '9060b6ec90dxxxxxxxxxxxxx' })

http.createServer((req, res) => {
  handler(req, res, (err) => {
    res.statusCode = 404
    res.end(err)
  })
}).listen(8001)

handler.on('error', err => {
  console.error('Error:', err.message)
})

handler.on('Push Hook', event => {
  console.log('Received a push event for %s to %s', event.payload.repository.name, event.payload.ref)
    // run_cmd('sh', ['./auto_shell.sh',event.payload.repository.name], function(text){ console.log(text) });
})

function run_cmd(cmd, args, callback) {
  const spawn = require('child_process').spawn
  const child = spawn(cmd, args)
  let resp = ""
  child.stdout.on('data', buffer => { resp += buffer.toString() })
  child.stdout.on('end', () => { callback (resp) })
}